package com.li.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.li.DTO.LoginDTO;
import com.li.VO.LoginVO;
import com.li.pojo.Company;
import com.li.pojo.Employee;
import com.li.result.Result;
import com.li.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;

/**
 * @Author: zhiqingLi
 * @Description: 登录注册接口
 * @Date: Created in 0:44 2024/3/13
 **/
@RestController
@Slf4j
public class LoginController {

    @Value("${li}")
    private String secret;

    @Autowired
    private LoginService loginService;

    //登录
    @PostMapping("/login")
    public Result<LoginVO> login(@RequestBody LoginDTO loginDTO) {
        Employee employee = loginService.login(loginDTO);
        //登录成功之后返回一个token返回给前端
        Calendar instance = Calendar.getInstance(); //日历类
        instance.add(Calendar.HOUR,5); //有效期是 2个小时
        String token = JWT.create().withClaim("companyId", employee.getCompanyId())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secret));
        //返回给前端
        LoginVO build = LoginVO.builder().token(token).name(employee.getName()).build();
        return Result.success(build);
    }

    //注册 实际实现注册公司 之后这个账号密码就是最高的系统管理员
    @PostMapping("/enrol")
    public Result enrol(@RequestBody Company company) {
        Integer i = loginService.enrol(company);
        return Result.success();
    }
}
